﻿// 通知系统
class NotificationSystem {
    constructor() {
        this.notifications = [];
        this.unreadCount = 0;
        this.setupEventListeners();
        this.initializeWebSocket();
    }

    setupEventListeners() {
        const notificationToggle = document.getElementById('notification-toggle');
        const notificationDropdown = document.querySelector('.notification-dropdown');
        const markAllRead = document.querySelector('.mark-all-read');

        notificationToggle.addEventListener('click', (e) => {
            e.preventDefault();
            notificationDropdown.classList.toggle('hidden');
        });

        markAllRead.addEventListener('click', () => {
            this.markAllAsRead();
        });

        // 点击外部关闭通知下拉框
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.notification-wrapper')) {
                notificationDropdown.classList.add('hidden');
            }
        });
    }

    initializeWebSocket() {
        // 实际使用时替换为你的WebSocket服务器地址
        this.ws = new WebSocket('ws://your-websocket-server');

        this.ws.onmessage = (event) => {
            const notification = JSON.parse(event.data);
            this.addNotification(notification);
        };
    }

    addNotification(notification) {
        this.notifications.unshift(notification);
        this.unreadCount++;
        this.updateNotificationBadge();
        this.renderNotification(notification);
    }

    renderNotification(notification) {
        const notificationList = document.querySelector('.notification-list');
        const notificationElement = document.createElement('div');
        notificationElement.className = 'notification-item unread';
        notificationElement.innerHTML = `
            <img src="${notification.avatar}" alt="通知头像" class="notification-avatar">
            <div class="notification-content">
                <p>${notification.message}</p>
                <span class="notification-time">${this.formatTime(notification.time)}</span>
            </div>
        `;
        notificationList.insertBefore(notificationElement, notificationList.firstChild);
    }

    markAllAsRead() {
        this.unreadCount = 0;
        this.updateNotificationBadge();
        document.querySelectorAll('.notification-item.unread').forEach(item => {
            item.classList.remove('unread');
        });
    }

    updateNotificationBadge() {
        const badge = document.querySelector('.notification-badge');
        badge.textContent = this.unreadCount;
        badge.style.display = this.unreadCount > 0 ? 'block' : 'none';
    }

    formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;

        if (diff < 60000) return '刚刚';
        if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
        if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
        return `${Math.floor(diff / 86400000)}天前`;
    }
}

// 动态加载系统
class InfiniteScroll {
    constructor() {
        this.page = 1;
        this.loading = false;
        this.hasMore = true;
        this.setupScrollListener();
    }

    setupScrollListener() {
        window.addEventListener('scroll', () => {
            if (this.loading || !this.hasMore) return;

            const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
            if (scrollTop + clientHeight >= scrollHeight - 100) {
                this.loadMorePosts();
            }
        });
    }

    async loadMorePosts() {
        this.loading = true;
        this.showLoader();

        try {
            // 实际使用时替换为你的API端点
            const response = await fetch(`/api/posts?page=${this.page}`);
            const data = await response.json();

            if (data.posts.length === 0) {
                this.hasMore = false;
                return;
            }

            this.renderPosts(data.posts);
            this.page++;
        } catch (error) {
            console.error('加载帖子失败:', error);
        } finally {
            this.hideLoader();
            this.loading = false;
        }
    }

    renderPosts(posts) {
        const postsContainer = document.querySelector('.posts');
        posts.forEach(post => {
            const postElement = this.createPostElement(post);
            postsContainer.appendChild(postElement);
        });
    }

    createPostElement(post) {
        const article = document.createElement('article');
        article.className = 'post';
        article.innerHTML = `
            <div class="post-header">
                <img src="${post.avatar}" alt="用户头像" class="post-avatar">
                <div class="post-info">
                    <h4>${post.username}</h4>
                    <span class="post-time">${this.formatTime(post.timestamp)}</span>
                </div>
            </div>
            <div class="post-content">${post.content}</div>
            ${post.images ? this.renderImages(post.images) : ''}
            <div class="post-actions">
                <button class="action-btn"><i class="far fa-heart"></i> 点赞</button>
                <button class="action-btn comment-toggle"><i class="far fa-comment"></i> 评论</button>
                <button class="action-btn"><i class="far fa-share"></i> 分享</button>
            </div>
        `;
        return article;
    }

    renderImages(images) {
        return `
            <div class="post-images">
                ${images.map(img => `<img src="${img}" alt="发布图片">`).join('')}
            </div>
        `;
    }

    showLoader() {
        const loader = document.querySelector('.loading-spinner');
        loader.classList.remove('hidden');
    }

    hideLoader() {
        const loader = document.querySelector('.loading-spinner');
        loader.classList.add('hidden');
    }

    formatTime(timestamp) {
        // 使用与通知系统相同的时间格式化函数
        return new NotificationSystem().formatTime(timestamp);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    const notificationSystem = new NotificationSystem();
    const infiniteScroll = new InfiniteScroll();
}); 